﻿using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using ASCompletion.Model;
using ASCompletion.Completion;

namespace MultiGenerator
{
    public partial class PluginUI : Form
    {
		public string[] methodsNames;
		
		private ClassModel contextClass;

        public PluginUI()
        {
            InitializeComponent();
            CenterToParent();
        }
		
		public void FillMemberList()
		{
			foreach (MemberModel item in contextClass.Members)
			{
				if ((item.Flags & FlagType.Variable) > 0)
				{
					ListViewItem row = new ListViewItem(item.Name);
					row.Checked = true;
					
					this.membersList.Items.Add(row);
				}
			}
		}
		
        public ClassModel ContextClass
        {
            set { this.contextClass = value; }
        }

        /// <summary>
        /// Check if the given name alreay exists in the class scope
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private bool exists(string name)
        {
            foreach(MemberModel item in contextClass.Members)
            {
                if (item.Name == name) return true;
            }
            return false;
        }

        private Boolean validateName(string name)
        {
			return /*name != contextMember.Name &&*/ name.Length > 0 && Regex.Match(name, "^[a-zA-Z_$][a-zA-Z0-9_$]+$").Success && exists(name) == false;
        }

        private void okButton_Click(object sender, EventArgs e)
        {
			//TODO check if member exist, rename functionality, move code into PluginMain
			
			int count = this.membersList.Items.Count;
			
			if (this.accessor.Checked) methodsNames = new string[count];
			
			for (int i = 0; i < count; i++)
			{
				if (this.membersList.Items[i].Checked)
				{
					if (this.setter.Checked) checkForCreate(this.membersList.Items[i].Text, GeneratorJobType.Setter);
					else if (this.getter.Checked) checkForCreate(this.membersList.Items[i].Text, GeneratorJobType.Getter);
					else if (this.getset.Checked) checkForCreate(this.membersList.Items[i].Text, GeneratorJobType.GetterSetter);
					else methodsNames[i] = this.membersList.Items[i].Text;
				}
			}
			
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

		private bool checkForCreate(string name, GeneratorJobType type)
		{
			foreach (MemberModel item in contextClass.Members)
			{
				if (item.Name == name)
				{
					//TODO check if member exist, rename functionality, move code into PluginMain
					ASGenerator.GenerateJob(type, item, contextClass, "");
					return true;
				}
			}
			
			return false;
		}
    }
}